<?php

namespace app\company\controller\user_profile\registration;

use app\BaseController;
use app\common\Message;
use app\model\iot_model\IotRoom;
use app\model\MessageModel;
use app\model\UnitModel;
use app\model\user_profile_model\UserProfileRecode;
use app\model\UserModel;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Registration extends BaseController
{
    use Message;

    /**
     * 获取单位列表
     * @return bool|string
     */
    public function getUnitList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'areas_id|ID' => 'require|integer|max:11',
            ]);
            $where = [];
            if(!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$param['areas_id']];
            $UnitModel = new UnitModel();
            $UserModel = new UserModel();
            $data = $UnitModel->field('id,name,banner,level,province_name,city_name,area_name')->where($where)->paginate($param['pageSize']);
            foreach ($data as &$item) {
                 $userWhere = [
                     ['unit_id','=',$item['id']],
                     ['status','=',1],
                 ];
                $item['user_num'] = $UserModel->where($userWhere)->count();
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 新增查阅登录记录
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addRecord(): bool|string
    {
        $param = $this->request->param();
        $uid = $this->userData['id'];
        $role_mode = $this->userData['role_mode'];
        $unit_id = $param['unit_id'];
        $key = ['password','num','remark','img','unit_id'];
        foreach($key as $item){
            if(check_array_key($item,$param)){
                $insert[$item] = $param[$item];
            }else{
                return error('缺少参数！');
            }
        }
        //验证密码是否正确
        if (isset($param['password']) && !empty($param['password'])) {
            $param['password'] = encrypt_password($param['password']);
        }
        //验证如果已经有一条有效数据
        $result = UserProfileRecode::query()->where([['uid','=',$uid],['is_expire','=',0],['unit_id','=',$unit_id]])->field('id,time,num')->find();
        if (!empty($result)) {
            return error('已有一条未过期的数据！');
        }
        $old = UserModel::query()->where('id',$uid)->value('password');
        if($param['password'] != $old){
            return error('密码错误！');
        }
        unset($insert['password']);
        $insert['time'] = time();
        $insert['unit_id'] = $unit_id;
        $insert['uid'] = $uid;
        $add = new UserProfileRecode();
        $message = new MessageModel();
        $messageAll = [];
        /*发送消息给对应单位的默认超管-开始*/
        $tempWhere[] = ['unit_id', '=', $unit_id];
        $tempWhere[] = ['not_del', '=', 1];
        $unit_uid = UserModel::query()->where($tempWhere)->value('id');
        $save_name = UserModel::query()->where('id',$uid)->value('name');
        //接收消息的人与自己ID相等，就是发给自己的【超管、管理员、咨询师:给自己发一条消息】
        $paragraph = '区域超级管理员:'.$save_name;
        $messageUid = $unit_uid; //接收消息人的ID【对方单位的默认超管】
        $content = $paragraph.'于'.date('Y-m-d',time()).'日期'.date('H:i:s',time()).'时间'.'申请了用户档案查阅权限，权限有效时长：'.$param['num'].'天。';
        $messageInfo = [
            'type' => 20,
            'title' => '申请查阅',
            'time' => time(),
            'content' => $content,
            'uid' => $messageUid
        ];
        $messageAll[] = $messageInfo;
        /*发送消息给对应单位的默认超管-结束*/

        /*发送消息给自己-开始*/
        $paragraphs = '您';
        $content = $paragraphs.'于'.date('Y-m-d',time()).'日期'.date('H:i:s',time()).'时间'.'申请了用户档案查阅权限，权限有效时长：'.$param['num'].'天。';
        $messageInfos = [
            'type' => 19,
            'title' => '申请查阅',
            'time' => time(),
            'content' => $content,
            'uid' => $uid,//接收消息人的ID【自己的ID】
        ];
        $messageAll[] = $messageInfos;
        /*发送消息给自己-结束*/
        $message->insertAll($messageAll);
        $ret = $add->insert($insert);
        return success($ret,'操作成功！');
    }

    /**
     * @throws DbException
     */
    public function recordList(): bool|string
    {
        $param = $this->request->param();
        $unit_id = $param['unit_id'];
        $key = ['page','pageSize','unit_id'];
        foreach($key as $item){
            if(!check_array_key($item,$param)){
                return error('缺少参数！');
            }
        }
        $where = [
            ['unit_id','=',$unit_id],
        ];
        $userProfileRecode = new UserProfileRecode();
        $ret = $userProfileRecode->where($where)
            ->with(['getUserInfo'])
            ->order('is_expire','time desc')
            ->field('id,uid,time,num,is_expire')
            ->paginate($param['pageSize']);
        return success($ret,'操作成功！');
    }

    /**
     * 刷新日期
     * @return bool|string
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function refreshRecord(): bool|string
    {
        $unit_id = $this->request->param('unit_id');
        $userProfileRecode = new UserProfileRecode();
        $where = [
            ['unit_id','=',$unit_id],
            ['is_expire','=',0],
        ];
        $list = $userProfileRecode->where($where)->field('id,time,num,is_expire')->select();
        if(count($list)>0){
            $ids = [];
            foreach($list as $item){
                $add_time = date('Y-m-d',$item['time']);//添加时间
                $end_time = $item['num']*24*60*60;//到期天数
                $new_time = strtotime($add_time.'23:59:59')+$end_time;
                if($new_time < time()){
                    //到期时间小于当前时间，这条记录更新为已过期
                    $update['id'] = $item['id'];
                    $update['is_expire'] = 1;
                    $ids[] = $update;
                }
            }
            if(!empty($ids)) $userProfileRecode->saveAll($ids);
        }
        return success([],'操作成功！');
    }
}